<template>
  <div class="data-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据管理</span>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 数据备份与恢复标签页 -->
        <el-tab-pane label="数据备份与恢复" name="backup">
          <div class="action-bar">
            <el-button type="primary" @click="manualBackup">手动备份</el-button>
            <el-button type="success" @click="showRestoreDialog">
              数据恢复
            </el-button>
            <el-button @click="showBackupSettingDialog">自动备份设置</el-button>
          </div>

          <el-divider content-position="left">备份历史</el-divider>

          <el-table :data="backupList" style="width: 100%" border>
            <el-table-column prop="id" label="备份ID" width="80" />
            <el-table-column prop="name" label="备份名称" width="150" />
            <el-table-column prop="type" label="备份类型" width="100">
              <template #default="scope">
                <el-tag
                  :type="scope.row.type === '手动' ? 'primary' : 'success'"
                >
                  {{ scope.row.type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="size" label="备份大小" width="100" />
            <el-table-column prop="createTime" label="备份时间" width="180" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === '成功' ? 'success' : 'danger'"
                >
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button type="primary" link @click="restoreData(scope.row)">
                  恢复
                </el-button>
                <el-button
                  type="success"
                  link
                  @click="downloadBackup(scope.row)"
                >
                  下载
                </el-button>
                <el-button type="danger" link @click="deleteBackup(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="backupCurrentPage"
              v-model:page-size="backupPageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="backupTotal"
              @size-change="handleBackupSizeChange"
              @current-change="handleBackupCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 数据清理标签页 -->
        <el-tab-pane label="数据清理" name="cleanup">
          <div class="action-bar">
            <el-button type="primary" @click="showCleanupDialog">
              数据清理
            </el-button>
            <el-button type="success" @click="showArchiveDialog">
              数据归档
            </el-button>
            <el-button @click="showCleanupSettingDialog">
              清理策略设置
            </el-button>
          </div>

          <el-divider content-position="left">清理历史</el-divider>

          <el-table :data="cleanupList" style="width: 100%" border>
            <el-table-column prop="id" label="任务ID" width="80" />
            <el-table-column prop="name" label="任务名称" width="150" />
            <el-table-column prop="type" label="任务类型" width="100">
              <template #default="scope">
                <el-tag
                  :type="scope.row.type === '清理' ? 'danger' : 'warning'"
                >
                  {{ scope.row.type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="dataType" label="数据类型" width="120" />
            <el-table-column prop="dataCount" label="数据量" width="100" />
            <el-table-column prop="createTime" label="执行时间" width="180" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === '成功' ? 'success' : 'danger'"
                >
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  @click="viewCleanupDetail(scope.row)"
                >
                  详情
                </el-button>
                <el-button
                  v-if="scope.row.type === '归档'"
                  type="success"
                  link
                  @click="restoreArchive(scope.row)"
                >
                  恢复
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="cleanupCurrentPage"
              v-model:page-size="cleanupPageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="cleanupTotal"
              @size-change="handleCleanupSizeChange"
              @current-change="handleCleanupCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 数据字典标签页 -->
        <el-tab-pane label="数据字典" name="dictionary">
          <div class="action-bar">
            <el-button type="primary" @click="showAddDictDialog">
              添加字典
            </el-button>
            <el-button type="success" @click="refreshDict">刷新</el-button>
            <el-button type="warning" @click="exportDict">导出</el-button>
          </div>

          <div class="dict-container">
            <div class="dict-list">
              <el-input
                v-model="dictSearch"
                placeholder="搜索字典类型"
                prefix-icon="Search"
                clearable
              />
              <el-scrollbar height="500px">
                <el-menu
                  :default-active="currentDictType"
                  @select="handleDictSelect"
                >
                  <el-menu-item
                    v-for="item in filteredDictTypes"
                    :key="item.code"
                    :index="item.code"
                  >
                    <el-icon><Document /></el-icon>
                    <span>{{ item.name }}</span>
                  </el-menu-item>
                </el-menu>
              </el-scrollbar>
            </div>

            <div class="dict-detail">
              <div class="dict-header" v-if="currentDictType">
                <h3>{{ getCurrentDictTypeName() }}</h3>
                <div>
                  <el-button
                    type="primary"
                    size="small"
                    @click="showAddDictItemDialog"
                  >
                    添加选项
                  </el-button>
                  <el-button type="danger" size="small" @click="deleteDictType">
                    删除字典
                  </el-button>
                </div>
              </div>

              <el-table
                v-if="currentDictType"
                :data="dictItemList"
                style="width: 100%"
                border
              >
                <el-table-column prop="label" label="名称" width="150" />
                <el-table-column prop="value" label="数值" width="100" />
                <el-table-column prop="sort" label="排序" width="80" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.status ? 'success' : 'danger'">
                      {{ scope.row.status ? '启用' : '禁用' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" />
                <el-table-column label="操作" width="150">
                  <template #default="scope">
                    <el-button
                      type="primary"
                      link
                      @click="editDictItem(scope.row)"
                    >
                      编辑
                    </el-button>
                    <el-button
                      type="danger"
                      link
                      @click="deleteDictItem(scope.row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <el-empty v-else description="请选择字典类型" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 数据恢复对话框 -->
    <el-dialog v-model="restoreDialogVisible" title="数据恢复" width="40%">
      <el-form :model="restoreForm" label-width="100px">
        <el-form-item label="恢复方式">
          <el-radio-group v-model="restoreForm.type">
            <el-radio label="backup">从备份恢复</el-radio>
            <el-radio label="file">从文件恢复</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="restoreForm.type === 'backup'" label="选择备份">
          <el-select
            v-model="restoreForm.backupId"
            placeholder="请选择备份文件"
          >
            <el-option
              v-for="item in backupList"
              :key="item.id"
              :label="item.name + ' (' + item.createTime + ')'"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="restoreForm.type === 'file'" label="上传备份文件">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">请上传.sql或.zip格式的备份文件</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="恢复选项">
          <el-checkbox v-model="restoreForm.clearBeforeRestore">
            恢复前清空现有数据
          </el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="restoreDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRestore">确认恢复</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 自动备份设置对话框 -->
    <el-dialog
      v-model="backupSettingDialogVisible"
      title="自动备份设置"
      width="40%"
    >
      <el-form :model="backupSettingForm" label-width="120px">
        <el-form-item label="启用自动备份">
          <el-switch v-model="backupSettingForm.enabled" />
        </el-form-item>

        <el-form-item label="备份频率">
          <el-select
            v-model="backupSettingForm.frequency"
            placeholder="请选择备份频率"
          >
            <el-option label="每天" value="daily" />
            <el-option label="每周" value="weekly" />
            <el-option label="每月" value="monthly" />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="backupSettingForm.frequency === 'weekly'"
          label="星期几"
        >
          <el-select
            v-model="backupSettingForm.weekday"
            placeholder="请选择星期几"
          >
            <el-option label="星期一" value="1" />
            <el-option label="星期二" value="2" />
            <el-option label="星期三" value="3" />
            <el-option label="星期四" value="4" />
            <el-option label="星期五" value="5" />
            <el-option label="星期六" value="6" />
            <el-option label="星期日" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="backupSettingForm.frequency === 'monthly'"
          label="每月几号"
        >
          <el-select v-model="backupSettingForm.day" placeholder="请选择日期">
            <el-option v-for="i in 31" :key="i" :label="i + '号'" :value="i" />
          </el-select>
        </el-form-item>

        <el-form-item label="备份时间">
          <el-time-picker
            v-model="backupSettingForm.time"
            format="HH:mm"
            placeholder="选择时间"
          />
        </el-form-item>

        <el-form-item label="保留备份数量">
          <el-input-number
            v-model="backupSettingForm.keepCount"
            :min="1"
            :max="100"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="backupSettingDialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="saveBackupSetting">
            保存设置
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 数据清理对话框 -->
    <el-dialog v-model="cleanupDialogVisible" title="数据清理" width="40%">
      <el-form :model="cleanupForm" label-width="100px">
        <el-form-item label="清理类型">
          <el-select
            v-model="cleanupForm.dataType"
            placeholder="请选择数据类型"
          >
            <el-option label="操作日志" value="operation_log" />
            <el-option label="登录日志" value="login_log" />
            <el-option label="审计日志" value="audit_log" />
            <el-option label="过期订单" value="expired_order" />
            <el-option label="临时文件" value="temp_file" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围">
          <el-radio-group v-model="cleanupForm.timeRange">
            <el-radio label="custom">自定义</el-radio>
            <el-radio label="30days">30天前</el-radio>
            <el-radio label="90days">90天前</el-radio>
            <el-radio label="180days">180天前</el-radio>
            <el-radio label="365days">一年前</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="cleanupForm.timeRange === 'custom'"
          label="自定义时间"
        >
          <el-date-picker
            v-model="cleanupForm.customTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>

        <el-form-item label="清理选项">
          <el-checkbox v-model="cleanupForm.backupBeforeCleanup">
            清理前备份
          </el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cleanupDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCleanup">确认清理</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 数据归档对话框 -->
    <el-dialog v-model="archiveDialogVisible" title="数据归档" width="40%">
      <el-form :model="archiveForm" label-width="100px">
        <el-form-item label="归档类型">
          <el-select
            v-model="archiveForm.dataType"
            placeholder="请选择数据类型"
          >
            <el-option label="操作日志" value="operation_log" />
            <el-option label="登录日志" value="login_log" />
            <el-option label="审计日志" value="audit_log" />
            <el-option label="历史订单" value="history_order" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围">
          <el-radio-group v-model="archiveForm.timeRange">
            <el-radio label="custom">自定义</el-radio>
            <el-radio label="30days">30天前</el-radio>
            <el-radio label="90days">90天前</el-radio>
            <el-radio label="180days">180天前</el-radio>
            <el-radio label="365days">一年前</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="archiveForm.timeRange === 'custom'"
          label="自定义时间"
        >
          <el-date-picker
            v-model="archiveForm.customTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>

        <el-form-item label="归档选项">
          <el-checkbox v-model="archiveForm.deleteAfterArchive">
            归档后删除原数据
          </el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="archiveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmArchive">确认归档</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 清理策略设置对话框 -->
    <el-dialog
      v-model="cleanupSettingDialogVisible"
      title="清理策略设置"
      width="40%"
    >
      <el-form :model="cleanupSettingForm" label-width="120px">
        <el-form-item label="启用自动清理">
          <el-switch v-model="cleanupSettingForm.enabled" />
        </el-form-item>

        <el-form-item label="清理频率">
          <el-select
            v-model="cleanupSettingForm.frequency"
            placeholder="请选择清理频率"
          >
            <el-option label="每周" value="weekly" />
            <el-option label="每月" value="monthly" />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="cleanupSettingForm.frequency === 'weekly'"
          label="星期几"
        >
          <el-select
            v-model="cleanupSettingForm.weekday"
            placeholder="请选择星期几"
          >
            <el-option label="星期一" value="1" />
            <el-option label="星期二" value="2" />
            <el-option label="星期三" value="3" />
            <el-option label="星期四" value="4" />
            <el-option label="星期五" value="5" />
            <el-option label="星期六" value="6" />
            <el-option label="星期日" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="cleanupSettingForm.frequency === 'monthly'"
          label="每月几号"
        >
          <el-select v-model="cleanupSettingForm.day" placeholder="请选择日期">
            <el-option v-for="i in 31" :key="i" :label="i + '号'" :value="i" />
          </el-select>
        </el-form-item>

        <el-form-item label="清理时间">
          <el-time-picker
            v-model="cleanupSettingForm.time"
            format="HH:mm"
            placeholder="选择时间"
          />
        </el-form-item>

        <el-divider>自动清理规则</el-divider>

        <div
          v-for="(rule, index) in cleanupSettingForm.rules"
          :key="index"
          class="rule-item"
        >
          <el-form-item :label="'规则' + (index + 1)">
            <div class="rule-content">
              <el-select
                v-model="rule.dataType"
                placeholder="数据类型"
                style="width: 120px"
              >
                <el-option label="操作日志" value="operation_log" />
                <el-option label="登录日志" value="login_log" />
                <el-option label="审计日志" value="audit_log" />
                <el-option label="过期订单" value="expired_order" />
                <el-option label="临时文件" value="temp_file" />
              </el-select>
              <span class="rule-text">保留最近</span>
              <el-input-number
                v-model="rule.keepDays"
                :min="1"
                :max="3650"
                style="width: 100px"
              />
              <span class="rule-text">天的数据</span>
              <el-button
                type="danger"
                icon="Delete"
                circle
                @click="removeCleanupRule(index)"
              />
            </div>
          </el-form-item>
        </div>

        <el-form-item>
          <el-button type="primary" @click="addCleanupRule">添加规则</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cleanupSettingDialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="saveCleanupSetting">
            保存设置
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加字典对话框 -->
    <el-dialog
      v-model="addDictDialogVisible"
      :title="editingDictType ? '编辑字典' : '添加字典'"
      width="40%"
    >
      <el-form
        :model="dictTypeForm"
        label-width="100px"
        :rules="dictTypeRules"
        ref="dictTypeFormRef"
      >
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="dictTypeForm.name" placeholder="请输入字典名称" />
        </el-form-item>

        <el-form-item label="字典编码" prop="code">
          <el-input
            v-model="dictTypeForm.code"
            placeholder="请输入字典编码"
            :disabled="editingDictType"
          />
        </el-form-item>

        <el-form-item label="字典描述" prop="description">
          <el-input
            v-model="dictTypeForm.description"
            type="textarea"
            placeholder="请输入字典描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDictDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveDictType">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加字典项对话框 -->
    <el-dialog
      v-model="addDictItemDialogVisible"
      :title="editingDictItem ? '编辑字典项' : '添加字典项'"
      width="40%"
    >
      <el-form
        :model="dictItemForm"
        label-width="100px"
        :rules="dictItemRules"
        ref="dictItemFormRef"
      >
        <el-form-item label="名称" prop="label">
          <el-input v-model="dictItemForm.label" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="数值" prop="value">
          <el-input v-model="dictItemForm.value" placeholder="请输入数值" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="dictItemForm.sort" :min="0" :max="999" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch v-model="dictItemForm.status" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="dictItemForm.remark"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDictItemDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveDictItem">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 清理详情对话框 -->
    <el-dialog
      v-model="cleanupDetailDialogVisible"
      title="清理详情"
      width="50%"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="任务ID">
          {{ currentCleanupDetail.id }}
        </el-descriptions-item>
        <el-descriptions-item label="任务名称">
          {{ currentCleanupDetail.name }}
        </el-descriptions-item>
        <el-descriptions-item label="任务类型">
          <el-tag
            :type="currentCleanupDetail.type === '清理' ? 'danger' : 'warning'"
          >
            {{ currentCleanupDetail.type }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="数据类型">
          {{ currentCleanupDetail.dataType }}
        </el-descriptions-item>
        <el-descriptions-item label="数据量">
          {{ currentCleanupDetail.dataCount }}
        </el-descriptions-item>
        <el-descriptions-item label="执行时间">
          {{ currentCleanupDetail.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag
            :type="
              currentCleanupDetail.status === '成功' ? 'success' : 'danger'
            "
          >
            {{ currentCleanupDetail.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="详细信息">
          <div style="white-space: pre-wrap">
            {{ currentCleanupDetail.detail }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cleanupDetailDialogVisible = false">
            关闭
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'

// 当前激活的标签页
const activeTab = ref('backup')

// ===== 数据备份与恢复相关 =====
// 备份列表数据
const backupList = ref([
  {
    id: '1001',
    name: '每日自动备份-20230601',
    type: '自动',
    size: '15.6MB',
    createTime: '2023-06-01 03:00:00',
    status: '成功',
  },
  {
    id: '1002',
    name: '手动备份-20230602',
    type: '手动',
    size: '16.2MB',
    createTime: '2023-06-02 15:30:45',
    status: '成功',
  },
  {
    id: '1003',
    name: '每周自动备份-20230604',
    type: '自动',
    size: '16.8MB',
    createTime: '2023-06-04 03:00:00',
    status: '成功',
  },
])

// 备份分页相关
const backupCurrentPage = ref(1)
const backupPageSize = ref(10)
const backupTotal = ref(100)

// 备份分页处理函数
const handleBackupSizeChange = (size: number) => {
  backupPageSize.value = size
  // 重新加载备份数据
  loadBackupData()
}

const handleBackupCurrentChange = (page: number) => {
  backupCurrentPage.value = page
  // 重新加载备份数据
  loadBackupData()
}

// 加载备份数据
const loadBackupData = () => {
  // TODO: 调用API获取备份数据
  // 这里使用模拟数据
  console.log(
    '加载备份数据，页码：',
    backupCurrentPage.value,
    '每页数量：',
    backupPageSize.value,
  )
}

// 数据恢复对话框
const restoreDialogVisible = ref(false)
const restoreForm = reactive({
  type: 'backup',
  backupId: '',
  file: null as File | null,
  clearBeforeRestore: false,
})

// 显示恢复对话框
const showRestoreDialog = () => {
  restoreDialogVisible.value = true
  restoreForm.type = 'backup'
  restoreForm.backupId = ''
  restoreForm.file = null
  restoreForm.clearBeforeRestore = false
}

// 处理文件上传
const handleFileChange = (file: any) => {
  restoreForm.file = file.raw
}

// 确认恢复数据
const confirmRestore = () => {
  if (restoreForm.type === 'backup' && !restoreForm.backupId) {
    ElMessage.warning('请选择备份文件')
    return
  }
  if (restoreForm.type === 'file' && !restoreForm.file) {
    ElMessage.warning('请上传备份文件')
    return
  }

  ElMessageBox.confirm('数据恢复操作将覆盖现有数据，是否继续？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // TODO: 调用API执行恢复操作
      ElMessage.success('数据恢复操作已提交，请稍后查看结果')
      restoreDialogVisible.value = false
    })
    .catch(() => {
      // 取消操作
    })
}

// 从备份恢复数据
const restoreData = (row: any) => {
  ElMessageBox.confirm(
    `确定要从备份 "${row.name}" 恢复数据吗？此操作将覆盖现有数据。`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      // TODO: 调用API执行恢复操作
      ElMessage.success(`已开始从备份 "${row.name}" 恢复数据，请稍后查看结果`)
    })
    .catch(() => {
      // 取消操作
    })
}

// 下载备份
const downloadBackup = (row: any) => {
  // TODO: 调用API下载备份文件
  ElMessage.success(`开始下载备份文件：${row.name}`)
}

// 删除备份
const deleteBackup = (row: any) => {
  ElMessageBox.confirm(`确定要删除备份 "${row.name}" 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'danger',
  })
    .then(() => {
      // TODO: 调用API删除备份
      ElMessage.success(`已删除备份：${row.name}`)
      // 重新加载备份数据
      loadBackupData()
    })
    .catch(() => {
      // 取消操作
    })
}

// 手动备份
const manualBackup = () => {
  ElMessageBox.confirm('确定要执行手动备份吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  })
    .then(() => {
      // TODO: 调用API执行手动备份
      ElMessage.success('手动备份操作已提交，请稍后查看结果')
      // 重新加载备份数据
      loadBackupData()
    })
    .catch(() => {
      // 取消操作
    })
}

// 自动备份设置对话框
const backupSettingDialogVisible = ref(false)
const backupSettingForm = reactive({
  enabled: true,
  frequency: 'daily',
  weekday: '1',
  day: 1,
  time: new Date(2023, 5, 1, 3, 0),
  keepCount: 30,
})

// 显示自动备份设置对话框
const showBackupSettingDialog = () => {
  backupSettingDialogVisible.value = true
}

// 保存自动备份设置
const saveBackupSetting = () => {
  // TODO: 调用API保存自动备份设置
  ElMessage.success('自动备份设置已保存')
  backupSettingDialogVisible.value = false
}

// ===== 数据清理相关 =====
// 清理列表数据
const cleanupList = ref([
  {
    id: '2001',
    name: '操作日志清理-20230601',
    type: '清理',
    dataType: '操作日志',
    dataCount: '1,234',
    createTime: '2023-06-01 04:00:00',
    status: '成功',
  },
  {
    id: '2002',
    name: '登录日志归档-20230602',
    type: '归档',
    dataType: '登录日志',
    dataCount: '5,678',
    createTime: '2023-06-02 04:00:00',
    status: '成功',
  },
  {
    id: '2003',
    name: '临时文件清理-20230603',
    type: '清理',
    dataType: '临时文件',
    dataCount: '256',
    createTime: '2023-06-03 04:00:00',
    status: '成功',
  },
])

// 清理分页相关
const cleanupCurrentPage = ref(1)
const cleanupPageSize = ref(10)
const cleanupTotal = ref(100)

// 清理分页处理函数
const handleCleanupSizeChange = (size: number) => {
  cleanupPageSize.value = size
  // 重新加载清理数据
  loadCleanupData()
}

const handleCleanupCurrentChange = (page: number) => {
  cleanupCurrentPage.value = page
  // 重新加载清理数据
  loadCleanupData()
}

// 加载清理数据
const loadCleanupData = () => {
  // TODO: 调用API获取清理数据
  // 这里使用模拟数据
  console.log(
    '加载清理数据，页码：',
    cleanupCurrentPage.value,
    '每页数量：',
    cleanupPageSize.value,
  )
}

// 数据清理对话框
const cleanupDialogVisible = ref(false)
const cleanupForm = reactive({
  dataType: 'operation_log',
  timeRange: '30days',
  customTimeRange: [] as Date[],
  backupBeforeCleanup: true,
})

// 显示清理对话框
const showCleanupDialog = () => {
  cleanupDialogVisible.value = true
  cleanupForm.dataType = 'operation_log'
  cleanupForm.timeRange = '30days'
  cleanupForm.customTimeRange = []
  cleanupForm.backupBeforeCleanup = true
}

// 确认清理数据
const confirmCleanup = () => {
  if (
    cleanupForm.timeRange === 'custom' &&
    (!cleanupForm.customTimeRange || cleanupForm.customTimeRange.length !== 2)
  ) {
    ElMessage.warning('请选择自定义时间范围')
    return
  }

  ElMessageBox.confirm('数据清理操作将永久删除数据，是否继续？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // TODO: 调用API执行清理操作
      ElMessage.success('数据清理操作已提交，请稍后查看结果')
      cleanupDialogVisible.value = false
      // 重新加载清理数据
      loadCleanupData()
    })
    .catch(() => {
      // 取消操作
    })
}

// 数据归档对话框
const archiveDialogVisible = ref(false)
const archiveForm = reactive({
  dataType: 'operation_log',
  timeRange: '30days',
  customTimeRange: [] as Date[],
  deleteAfterArchive: true,
})

// 显示归档对话框
const showArchiveDialog = () => {
  archiveDialogVisible.value = true
  archiveForm.dataType = 'operation_log'
  archiveForm.timeRange = '30days'
  archiveForm.customTimeRange = []
  archiveForm.deleteAfterArchive = true
}

// 确认归档数据
const confirmArchive = () => {
  if (
    archiveForm.timeRange === 'custom' &&
    (!archiveForm.customTimeRange || archiveForm.customTimeRange.length !== 2)
  ) {
    ElMessage.warning('请选择自定义时间范围')
    return
  }

  ElMessageBox.confirm('数据归档操作将移动数据到归档存储，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  })
    .then(() => {
      // TODO: 调用API执行归档操作
      ElMessage.success('数据归档操作已提交，请稍后查看结果')
      archiveDialogVisible.value = false
      // 重新加载清理数据
      loadCleanupData()
    })
    .catch(() => {
      // 取消操作
    })
}

// 恢复归档数据
const restoreArchive = (row: any) => {
  ElMessageBox.confirm(`确定要恢复归档 "${row.name}" 的数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  })
    .then(() => {
      // TODO: 调用API执行恢复归档操作
      ElMessage.success(`已开始恢复归档 "${row.name}" 的数据，请稍后查看结果`)
    })
    .catch(() => {
      // 取消操作
    })
}

// 清理详情对话框
const cleanupDetailDialogVisible = ref(false)
const currentCleanupDetail = reactive({
  id: '',
  name: '',
  type: '',
  dataType: '',
  dataCount: '',
  createTime: '',
  status: '',
  detail: '',
})

// 查看清理详情
const viewCleanupDetail = (row: any) => {
  // TODO: 调用API获取清理详情
  Object.assign(currentCleanupDetail, row)
  currentCleanupDetail.detail = `清理详情信息：\n- 开始时间：${
    row.createTime
  }\n- 结束时间：${row.createTime.split(' ')[0]} 04:05:30\n- 清理条件：${
    row.dataType
  } 30天前的数据\n- 清理数量：${
    row.dataCount
  } 条\n- 清理结果：成功\n- 备注：系统自动清理任务执行成功`
  cleanupDetailDialogVisible.value = true
}

// 清理策略设置对话框
const cleanupSettingDialogVisible = ref(false)
const cleanupSettingForm = reactive({
  enabled: true,
  frequency: 'weekly',
  weekday: '1',
  day: 1,
  time: new Date(2023, 5, 1, 4, 0),
  rules: [
    { dataType: 'operation_log', keepDays: 30 },
    { dataType: 'login_log', keepDays: 90 },
    { dataType: 'temp_file', keepDays: 7 },
  ],
})

// 显示清理策略设置对话框
const showCleanupSettingDialog = () => {
  cleanupSettingDialogVisible.value = true
}

// 添加清理规则
const addCleanupRule = () => {
  cleanupSettingForm.rules.push({ dataType: 'operation_log', keepDays: 30 })
}

// 删除清理规则
const removeCleanupRule = (index: number) => {
  cleanupSettingForm.rules.splice(index, 1)
}

// 保存清理策略设置
const saveCleanupSetting = () => {
  // TODO: 调用API保存清理策略设置
  ElMessage.success('清理策略设置已保存')
  cleanupSettingDialogVisible.value = false
}

// ===== 数据字典相关 =====
// 字典类型列表
const dictTypes = ref([
  { code: 'user_status', name: '用户状态', description: '用户状态字典' },
  { code: 'gender', name: '性别', description: '性别字典' },
  { code: 'sys_normal_disable', name: '系统开关', description: '系统开关状态' },
  { code: 'sys_user_sex', name: '用户性别', description: '用户性别列表' },
  { code: 'sys_show_hide', name: '显示状态', description: '显示隐藏状态' },
  { code: 'sys_yes_no', name: '系统是否', description: '系统是否列表' },
])

// 字典项列表
const dictItemList = ref([
  {
    dictCode: 'user_status',
    label: '正常',
    value: '0',
    sort: 1,
    status: true,
    remark: '正常状态',
  },
  {
    dictCode: 'user_status',
    label: '停用',
    value: '1',
    sort: 2,
    status: true,
    remark: '停用状态',
  },
])

// 字典搜索
const dictSearch = ref('')
const filteredDictTypes = computed(() => {
  if (!dictSearch.value) return dictTypes.value
  return dictTypes.value.filter(
    (item) =>
      item.name.toLowerCase().includes(dictSearch.value.toLowerCase()) ||
      item.code.toLowerCase().includes(dictSearch.value.toLowerCase()),
  )
})

// 当前选中的字典类型
const currentDictType = ref('')

// 获取当前字典类型名称
const getCurrentDictTypeName = () => {
  const dictType = dictTypes.value.find(
    (item) => item.code === currentDictType.value,
  )
  return dictType ? dictType.name : ''
}

// 选择字典类型
const handleDictSelect = (index: string) => {
  currentDictType.value = index
  loadDictItems(index)
}

// 加载字典项
const loadDictItems = (dictCode: string) => {
  // TODO: 调用API获取字典项
  // 这里使用模拟数据
  if (dictCode === 'gender') {
    dictItemList.value = [
      {
        dictCode: 'gender',
        label: '男',
        value: 'male',
        sort: 1,
        status: true,
        remark: '',
      },
      {
        dictCode: 'gender',
        label: '女',
        value: 'female',
        sort: 2,
        status: true,
        remark: '',
      },
      {
        dictCode: 'gender',
        label: '未知',
        value: 'unknown',
        sort: 3,
        status: true,
        remark: '',
      },
    ]
  } else if (dictCode === 'user_status') {
    dictItemList.value = [
      {
        dictCode: 'user_status',
        label: '正常',
        value: '0',
        sort: 1,
        status: true,
        remark: '正常状态',
      },
      {
        dictCode: 'user_status',
        label: '停用',
        value: '1',
        sort: 2,
        status: true,
        remark: '停用状态',
      },
    ]
  } else {
    dictItemList.value = []
  }
}

// 添加字典对话框
const addDictDialogVisible = ref(false)
const editingDictType = ref(false)
const dictTypeForm = reactive({
  name: '',
  code: '',
  description: '',
})

// 字典类型表单验证规则
const dictTypeRules = {
  name: [
    { required: true, message: '请输入字典名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入字典编码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    {
      pattern: /^[a-z][a-z0-9_]*$/,
      message: '编码必须以小写字母开头，只能包含小写字母、数字和下划线',
      trigger: 'blur',
    },
  ],
}

// 显示添加字典对话框
const showAddDictDialog = () => {
  editingDictType.value = false
  dictTypeForm.name = ''
  dictTypeForm.code = ''
  dictTypeForm.description = ''
  addDictDialogVisible.value = true
}

// 保存字典类型
const saveDictType = () => {
  // TODO: 调用API保存字典类型
  if (editingDictType.value) {
    ElMessage.success(`字典 "${dictTypeForm.name}" 已更新`)
  } else {
    dictTypes.value.push({
      code: dictTypeForm.code,
      name: dictTypeForm.name,
      description: dictTypeForm.description,
    })
    ElMessage.success(`字典 "${dictTypeForm.name}" 已添加`)
  }
  addDictDialogVisible.value = false
}

// 删除字典类型
const deleteDictType = () => {
  if (!currentDictType.value) return

  ElMessageBox.confirm(
    `确定要删除字典 "${getCurrentDictTypeName()}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      // TODO: 调用API删除字典类型
      dictTypes.value = dictTypes.value.filter(
        (item) => item.code !== currentDictType.value,
      )
      ElMessage.success(`字典 "${getCurrentDictTypeName()}" 已删除`)
      currentDictType.value = ''
      dictItemList.value = []
    })
    .catch(() => {
      // 取消操作
    })
}

// 添加字典项对话框
const addDictItemDialogVisible = ref(false)
const editingDictItem = ref(false)
const dictItemForm = reactive({
  id: '',
  dictCode: '',
  label: '',
  value: '',
  sort: 0,
  status: true,
  remark: '',
})

// 字典项表单验证规则
const dictItemRules = {
  label: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
  ],
  value: [
    { required: true, message: '请输入数值', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
  ],
}

// 显示添加字典项对话框
const showAddDictItemDialog = () => {
  if (!currentDictType.value) {
    ElMessage.warning('请先选择字典类型')
    return
  }

  editingDictItem.value = false
  dictItemForm.id = ''
  dictItemForm.dictCode = currentDictType.value
  dictItemForm.label = ''
  dictItemForm.value = ''
  dictItemForm.sort = dictItemList.value.length + 1
  dictItemForm.status = true
  dictItemForm.remark = ''
  addDictItemDialogVisible.value = true
}

// 编辑字典项
const editDictItem = (row: any) => {
  editingDictItem.value = true
  Object.assign(dictItemForm, row)
  addDictItemDialogVisible.value = true
}

// 保存字典项
const saveDictItem = () => {
  // TODO: 调用API保存字典项
  if (editingDictItem.value) {
    // 更新现有字典项
    const index = dictItemList.value.findIndex(
      (item) =>
        item.value === dictItemForm.value &&
        item.dictCode === dictItemForm.dictCode,
    )
    if (index !== -1) {
      dictItemList.value[index] = { ...dictItemForm }
    }
    ElMessage.success(`字典项 "${dictItemForm.label}" 已更新`)
  } else {
    // 添加新字典项
    dictItemList.value.push({ ...dictItemForm })
    ElMessage.success(`字典项 "${dictItemForm.label}" 已添加`)
  }
  addDictItemDialogVisible.value = false
}

// 删除字典项
const deleteDictItem = (row: any) => {
  ElMessageBox.confirm(`确定要删除字典项 "${row.label}" 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // TODO: 调用API删除字典项
      dictItemList.value = dictItemList.value.filter(
        (item) => !(item.value === row.value && item.dictCode === row.dictCode),
      )
      ElMessage.success(`字典项 "${row.label}" 已删除`)
    })
    .catch(() => {
      // 取消操作
    })
}

// 刷新字典
const refreshDict = () => {
  // TODO: 调用API刷新字典缓存
  ElMessage.success('字典缓存已刷新')
}

// 导出字典
const exportDict = () => {
  // TODO: 调用API导出字典
  ElMessage.success('字典数据导出中，请稍后查看下载结果')
}

// 页面加载时初始化数据
onMounted(() => {
  loadBackupData()
  loadCleanupData()
})
</script>
<style scoped>
.data-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dict-container {
  display: flex;
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.dict-list {
  width: 250px;
  border-right: 1px solid #ebeef5;
  padding: 10px;
}

.dict-detail {
  flex: 1;
  padding: 10px 20px;
}

.dict-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.rule-item {
  margin-bottom: 10px;
}

.rule-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.rule-text {
  margin: 0 5px;
}
</style>
